#!/usr/bin/python2.5
#
# (c) 2009 - Chip Turner
#
# Apache License, blah blah, it's a few hundred lines of python.

import logging
import os
import time
import sys
import optparse
import textwrap

import armory_lib

from xml.etree import ElementTree

def main(args):
  parser = optparse.OptionParser(__doc__)
  parser.add_option("-r", "--realm", help="realm player or guild is on")
  parser.add_option("", "--eu", help="Use EU Armory instead of US armory",
                    action="store_true")
  parser.add_option("-g", "--guild", help="guild name to extract data for")
  parser.add_option("-m", "--maxrank", help="maximum rank to show results for (numeric, gm=0)",
                    type=int)
  parser.add_option("-l", "--level", help="minimum level to show results for", type=int, default=80)
  parser.add_option("-x", "--exclude", help="exclude this user", action="append")
  parser.add_option("-v", "--verbose", help="show debugging output", action="store_true")
  parser.add_option("", "--ranks", help="file containing guild ranks, in descending order, one per line")

  options, args = parser.parse_args(args)

  if options.verbose:
    armory_lib.InitLogging(logging.DEBUG)
  else:
    armory_lib.InitLogging()

  if options.eu:
    armory_interface = armory_lib.ArmoryInterface("eu")
  else:
    armory_interface = armory_lib.ArmoryInterface("us")

  ranks = dict()
  if options.ranks:
    idx = 0
    for line in open(options.ranks):
      ranks[idx] = line.strip()
      idx += 1

  root = ElementTree.Element("roster")
  root.text = "\n  "
  root.set("generated", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())))

  members = armory_interface.ParseRoster(options.realm, options.guild)
  matching_members = 0
  for name, level, race_id, class_id, rank in members:
    if level < options.level: continue
    if options.maxrank and rank > options.maxrank: continue
    if options.exclude and name in options.exclude: continue
    matching_members += 1

    race_name, class_name = armory_lib.ReadableRaceAndClass(race_id, class_id)

    char_info = armory_interface.ParseCharacter(options.realm, name)
    specs = char_info.GetSpecs()

    char = ElementTree.SubElement(root, "member")
    FastSubElement(char, "name", name)
    FastSubElement(char, "level", level)
    FastSubElement(char, "race", race_name)
    FastSubElement(char, "class", class_name)
    if specs:
      FastSubElement(char, "current_spec", specs[0][0])
    FastSubElement(char, "rank", ranks.get(rank, rank)).tail = "\n  "
    char.tail = "\n  "
    char.text = "\n    "
  char.tail = "\n"

  tree = ElementTree.ElementTree(root)
  print ElementTree.tostring(root)

def FastSubElement(node, child_name, child_value):
  child = ElementTree.SubElement(node, child_name)
  child.text = str(child_value)
  child.tail = "\n    "
  return child

if __name__ == '__main__':
  main(sys.argv[1:])
